package org.or5e.service.core.ds.login;

import java.util.Calendar;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.or5e.service.core.dao.UserLogin;
import org.or5e.service.core.ds.BasicDataSource;
import org.or5e.service.core.ds.DataSourceFactory;
import org.or5e.service.core.sm.DAOSession;
import org.or5e.service.core.sm.SessionManager;

public class LoginDataSourceImpl extends BasicDataSource implements LoginDataSource {
	public LoginDataSourceImpl(SessionFactory sessionFactory, SessionManager sessionManager) {
		super(sessionFactory, sessionManager);
	}

	@Override
	public String authenticateUser(UserLogin uLogin) {
		String sessionID = null;
		if(uLogin == null) return sessionID;
		
		Session session = this.sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<UserLogin> query = (List<UserLogin>) session.createQuery(
				"from UserLogin u where u.loginID='"+uLogin.getLoginID()+"' and u.password='"+uLogin.getPassword()+"' and u.status=true").list();
		if(query != null) {
			for (UserLogin userLogin : query) {
				sessionID = Calendar.getInstance().getTimeInMillis()+uLogin.getLoginID().substring(0, 3);
				this.sessionManager.createNewSession(sessionID, userLogin);
				break;
			}
		}
		session.flush();
		session.close();
		return sessionID;
	}

	@Override
	public Boolean isSessionActive(String sessionID) {
		DAOSession daoSession = this.sessionManager.getSession(sessionID);
		if(daoSession == null) return false;
		synchronized(daoSession) {
			daoSession.accesedNow();
			return Boolean.valueOf(true);
		}
	}

	@Override
	public String getName() {
		return "LoginDataSourceImpl";
	}

	@Override
	public UserLogin getUserInfo(Integer userID) {
		Session session = sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<UserLogin> uLogin = (List<UserLogin>) session.createQuery("from UserLogin u where u.userID="+userID.intValue()).list();
		session.flush();
		session.clear();
		session.close();
		return uLogin != null && uLogin.size() > 0 ? uLogin.get(0) : null;
	}
	
	public static void main(String[] args) {
		LoginDataSource fMaster = (LoginDataSource)DataSourceFactory.getDataSourceFactory().getDataSource(LoginDataSource.class);
		UserLogin userInfo = fMaster.getUserInfo(10010);
		if(userInfo != null) {
			System.out.println("User Name:"+userInfo.getLoginID());
		}
		fMaster.closeDataSource();
	}
}